<template>
  <div class="vehicle-container">
    <a-card class="vehicle-card" :bordered="false">
      <!-- 顶部标题和操作区 -->
      <div class="header-section">
        <h2 class="page-title">车辆管理</h2>
        <div class="table-operations">
          <a-row :gutter="16" align="middle">
            <a-col :span="8">
              <a-input-search
                v-model:value="search"
                placeholder="搜索车辆信息..."
                @search="fetchVehicleList"
                enter-button
                size="large"
                class="search-input"
              />
            </a-col>
            <a-col :span="16" style="text-align: right">
              <a-button type="primary" size="large" @click="showAddModal" class="add-button">
                <plus-outlined />
                新增车辆
              </a-button>
            </a-col>
          </a-row>
        </div>
      </div>

      <!-- 车辆表格 -->
      <a-table
        :columns="columns"
        :data-source="vehicleList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        class="custom-table"
        :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : '')"
      >
        <!-- 自定义列显示 -->
        <template v-slot:bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'licensePlate'">
            <span class="license-plate">{{ record.licensePlate }}</span>
          </template>
          <template v-if="column.dataIndex === 'productionDate'">
            <span class="date-text">
              {{ record.productionDate ? dayjs(record.productionDate).format('YYYY-MM-DD') : '--' }}
            </span>
          </template>
          <template v-if="column.dataIndex === 'driverId'">
            <a-tag color="blue">{{ getDriverName(record.driverId) }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'useStatus'">
            <a-tag :color="record.useStatus === 1 ? 'red' : 'green'">
              {{ record.useStatus === 1 ? '使用中' : '未使用' }}
            </a-tag>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-space>
              <a-button type="link" @click="showEditModal(record)" class="edit-button">
                <edit-outlined />
                编辑
              </a-button>
              <a-popconfirm
                title="确定要删除这辆车吗？"
                @confirm="handleDelete(record.vehicleId)"
                ok-text="确定"
                cancel-text="取消"
              >
                <a-button type="link" danger class="delete-button">
                  <delete-outlined />
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>

      <!-- 添加/编辑车辆模态框 -->
      <a-modal
        :title="modalTitle"
        :open="modalVisible"
        @ok="handleModalOk"
        @cancel="handleModalCancel"
        class="vehicle-modal"
        :maskClosable="false"
        :width="500"
      >
        <a-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-form-item label="车牌号" name="licensePlate">
            <a-input 
              v-model:value="formData.licensePlate" 
              placeholder="请输入车牌号"
              class="custom-input"
            />
          </a-form-item>
          <a-form-item label="生产厂家" name="manufacturer">
            <a-input 
              v-model:value="formData.manufacturer" 
              placeholder="请输入生产厂家"
              class="custom-input"
            />
          </a-form-item>
          <a-form-item label="生产日期" name="productionDate">
            <a-date-picker
              v-model:value="formData.productionDate" 
              placeholder="请选择生产日期"
              :locale="zhCN"
              format="YYYY-MM-DD"
              class="custom-date-picker"
            />
          </a-form-item>
          <a-form-item label="搭载人数" name="loadCapacity">
            <a-input-number
              v-model:value="formData.loadCapacity"
              placeholder="请输入搭载人数"
              class="custom-input-number"
              :min="0"
              addonAfter="人"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item label="驾驶员" name="driverId">
            <a-select
              v-model:value="formData.driverId"
              placeholder="请选择驾驶员"
              class="custom-select"
              show-search
              :filter-option="filterDriverOption"
            >
              <a-select-option
                v-for="dr in getDriverList"
                :key="dr.driverId"
                :value="dr.driverId"
              >
                {{ dr.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="使用状态" name="useStatus">
            <a-radio-group v-model:value="formData.useStatus">
              <a-radio :value="1">使用中</a-radio>
              <a-radio :value="0">未使用</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { list,add,del,update} from '@/api/vehicle'
import { getDataList } from '@/api/data'
import dayjs from 'dayjs'
import zhCN from 'ant-design-vue/es/date-picker/locale/zh_CN'

// 表格列定义
const columns = [
  {
    title: '车牌号',
    dataIndex: 'licensePlate',
    key: 'licensePlate',
  },
  {
    title: '品牌',
    dataIndex: 'manufacturer',
    key: 'manufacturer',
  },
  {
    title: '生产日期',
    dataIndex: 'productionDate',
    key: 'productionDate',
    customRender: ({ text }) => text ? dayjs(text).format('YYYY-MM-DD') : '--'
  },
  {
    title: '搭载人数',
    dataIndex: 'loadCapacity',
    key: 'loadCapacity',
  },
  {
    title: '驾驶员',
    dataIndex: 'driverId',
    key: 'driverId',
  },
  {
    title: "使用状态",
    dataIndex: 'useStatus',
    key: 'useStatus',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
  },
]

// 数据相关
const loading = ref(false)
const vehicleList = ref([])
const getDriverList=ref([])
const driverList = ref([])
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
})
const search=ref('')
// 模态框相关
const modalVisible = ref(false)
const modalTitle = ref('添加驾驶员')
const formRef = ref(null)
const formData = ref({
  vehicleId: '',
  licensePlate: '',
  manufacturer: '',
  productionDate: null,
  loadCapacity: '',
  driverId: '',
  useStatus: ''
})

// 表单验证规则
const rules = {
  licensePlate: [
    { required: true, message: '请输入车牌号', trigger: 'blur' },
    { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{4,5}[A-Z0-9挂学警港澳]$/, message: '请输入正确的车牌号', trigger: 'blur' }
  ],
  manufacturer: [
    { required: true, message: '请输入生产厂家', trigger: 'blur' }
  ],
  productionDate: [
    { required: true, message: '请选择生产日期', trigger: 'change' }
  ],
  loadCapacity: [
    { required: true, message: '请输入载重量', trigger: 'blur' },
    { pattern: /^\d+$/, message: '载重量必须为数字', trigger: 'blur' }
  ],
  driverId: [
    { required: true, message: '请选择驾驶员', trigger: 'change' }
  ],
  useStatus: [
    { required: true, message: '请选择使用状态', trigger: 'change' },
  ],
}

const DataList=async()=>{
      const res =await getDataList();
      console.log(res)
      if(res.code===200){
          getDriverList.value=res.data.driverInfoList
      }
}
// 获取驾驶员名称
const getDriverName = (driverId) => {
  const driver = getDriverList.value.find(dr => dr.driverId === driverId)
  return driver ? driver.name : '-'
}

// 获取车辆列表
const fetchVehicleList = async () => {
  loading.value = true
  try {
    const res = await list({
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize,
      search: search.value
    })
    vehicleList.value = res.data.records
    pagination.value.total = res.data.total

  } catch (error) {
    message.error('获取车辆列表失败')
  } finally {
    loading.value = false
  }
}

// 表格分页变化
const handleTableChange = (pag) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  fetchVehicleList()
}

// 显示添加模态框
const showAddModal = () => {
  modalTitle.value = '添加车辆'
  formData.value = {
    vehicleId: '',
    licensePlate: '',
    manufacturer: '',
    productionDate: null,
    loadCapacity: '',
    driverId: '',
    useStatus:0
  }
  modalVisible.value = true
}

// 显示编辑模态框
const showEditModal = (record) => {
  modalTitle.value = '编辑车辆'
  formData.value = {
    ...record,
    vehicleId: record.vehicleId,
    productionDate: record.productionDate ? dayjs(record.productionDate) : null,
  }
  modalVisible.value = true
}

// 处理模态框确认
const handleModalOk = () => {
  formRef.value?.validate().then(async () => {
    try {
      const submitData = {
        ...formData.value,
        productionDate: formData.value.productionDate ? formData.value.productionDate.format('YYYY-MM-DD') : null,
      }
      
      console.log('提交的数据:', submitData)
      
      const res = formData.value.vehicleId 
        ? await update(submitData)
        : await add(submitData)

        console.log(res)
      if(res.code === 200) {
        message.success(`${modalTitle.value}成功`)
        modalVisible.value = false
        fetchVehicleList()
      } else {
        message.error(res.msg || `${modalTitle.value}失败`)
      }
    } catch (error) {
      console.error('操作失败:', error)
      message.error(`${modalTitle.value}失败`)
    }
  })
}

// 处理模态框取消
const handleModalCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}

// 处理删除车辆
const handleDelete = async (vehicleId) => {
  try {
    const res = await del(vehicleId)
    if(res.code === 200) {
      message.success('删除成功')
      await fetchVehicleList()
    }
  } catch (error) {
    message.error('删除失败')
  }
}

// 添加驾驶员筛选方法
const filterDriverOption = (input, option) => {
  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

// 页面加载时获取列表数据
onMounted(() => {
  fetchVehicleList()
  DataList()
})
</script>

<style scoped>
.vehicle-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.vehicle-card {
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.header-section {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  color: #1f1f1f;
  margin-bottom: 24px;
  font-weight: 500;
}

.search-input {
  width: 100%;
  :deep(.ant-input) {
    border-radius: 4px;
  }
}

.add-button {
  border-radius: 4px;
  height: 40px;
  font-weight: 500;
  box-shadow: 0 2px 0 rgba(0, 0, 0, 0.045);
}

.custom-table {
  :deep(.ant-table-thead > tr > th) {
    background: #fafafa;
    font-weight: 500;
  }
  
  :deep(.table-striped) {
    background-color: #fafafa;
  }
}

.license-plate {
  font-family: 'Roboto Mono', monospace;
  font-weight: 500;
  color: #1890ff;
  background: #e6f7ff;
  padding: 4px 8px;
  border-radius: 4px;
}

.date-text {
  color: #666;
}

.edit-button {
  color: #1890ff;
}

.delete-button {
  color: #ff4d4f;
}

.vehicle-modal {
  :deep(.ant-modal-header) {
    border-bottom: 1px solid #f0f0f0;
    padding: 16px 24px;
  }
  
  :deep(.ant-modal-footer) {
    border-top: 1px solid #f0f0f0;
    padding: 16px 24px;
  }
}

.custom-input,
.custom-select,
.custom-date-picker,
.custom-input-number {
  width: 100%;
  :deep(.ant-input),
  :deep(.ant-select-selector),
  :deep(.ant-picker) {
    border-radius: 4px;
  }
}

/* 添加动画效果 */
.add-button,
.edit-button,
.delete-button {
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-1px);
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .vehicle-container {
    padding: 12px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .header-section {
    margin-bottom: 16px;
  }
  
  .search-input,
  .add-button {
    margin-bottom: 12px;
  }
}
</style>